package com.chenchao.thread;

/**
 * @encoding : UTF-8
 * @Time : 2020/11/18 16:18
 * @Author : Chen Chao
 * @File : javaSE.com.chenchao.javathread.Test19.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 信号灯法
 */
public class Test19 {
    public static void main(String[] args) {
        TrafficLight trafficLight = new TrafficLight();
        Thread thread1 = new Thread(new Pedestrian(trafficLight));
        Thread thread2 = new Thread(new Car(trafficLight));
        thread1.start();
        thread2.start();
    }
}

/**
 * 行人
 */
class Pedestrian implements Runnable {
    private TrafficLight trafficLight;
    public Pedestrian(TrafficLight trafficLight) {
        this.trafficLight = trafficLight;
    }
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            trafficLight.green();
        }
    }
}

/**
 * 车辆
 */
class Car implements Runnable {
    private TrafficLight trafficLight;

    public Car(TrafficLight trafficLight) {
        this.trafficLight = trafficLight;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            trafficLight.red();
        }
    }
}

/**
 * 信号灯
 */
class TrafficLight {
    boolean flag = true;
    //true为绿灯，false为红灯
    public synchronized void green() {
        if (!flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("绿灯，行人走");
        flag = !flag;
        this.notify();
    }
    public synchronized void red() {
        if (flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("红灯，车辆走");
        flag = !flag;
        this.notify();
    }
}